package com.kc.gb.device.controller;

import com.kc.gb.base.dto.Result;
import com.kc.gb.device.common.utils.I18NHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin/i18n")
public class I18NAdminController {

    @GetMapping("/mappings/default")
    public Result mappings() throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Locale locale = I18NHelper.getDefaultLocale();
        Map<String,String> mappings =  I18NHelper.getI18NMap(locale);
        return Result.success(mappings);
    }

    @GetMapping("/language/change")
    public Result mappings(HttpServletRequest request, @RequestParam String language) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        Locale locale = Locale.forLanguageTag(language);
        Locale.setDefault(locale);
        I18NHelper.setDefaultLocale(locale);
        // 获取 SessionLocaleResolver
        Locale sessionLocale = (Locale) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
        log.info("ChangeLanguage|Before:{} After:{} Session:{}",locale, LocaleContextHolder.getLocale(),sessionLocale);
        return Result.success();
    }


}
